import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import pandas as pd
import random
import threading
import time
import os
from PIL import Image, ImageTk
import sys


class LotteryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("幸运抽奖系统")
        self.root.geometry("900x700")
        self.root.resizable(True, True)

        # 设置应用图标（如果有）
        try:
            self.root.iconbitmap("lottery_icon.ico")
        except:
            pass

        # 初始化变量
        self.participants = []
        self.winners = []
        self.is_rolling = False
        self.current_display_index = 0
        self.display_list = []
        self.roll_speed = 100  # 初始滚动速度(毫秒)
        self.max_speed = 50  # 最大滚动速度
        self.min_speed = 200  # 最小滚动速度

        # 创建UI
        self.create_widgets()

        # 加载一些示例数据
        self.load_sample_data()

    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

        # 创建控制面板
        control_frame = ttk.LabelFrame(main_frame, text="控制面板")
        control_frame.pack(fill=tk.X, pady=(0, 15))

        # 导入按钮
        self.import_btn = ttk.Button(control_frame, text="导入Excel名单", command=self.import_excel)
        self.import_btn.pack(side=tk.LEFT, padx=5, pady=5)

        # 人数设置
        ttk.Label(control_frame, text="抽取人数:").pack(side=tk.LEFT, padx=(15, 5), pady=5)
        self.draw_count = tk.IntVar(value=1)
        self.count_spin = ttk.Spinbox(control_frame, from_=1, to=10, width=5, textvariable=self.draw_count)
        self.count_spin.pack(side=tk.LEFT, padx=5, pady=5)

        # 开始按钮
        self.start_btn = ttk.Button(control_frame, text="开始抽奖", command=self.start_lottery, state=tk.DISABLED)
        self.start_btn.pack(side=tk.LEFT, padx=15, pady=5)

        # 停止按钮
        self.stop_btn = ttk.Button(control_frame, text="停止", command=self.stop_lottery, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=5, pady=5)

        # 重置按钮
        self.reset_btn = ttk.Button(control_frame, text="重置", command=self.reset_lottery)
        self.reset_btn.pack(side=tk.LEFT, padx=15, pady=5)

        # 抽奖显示区域
        display_frame = ttk.LabelFrame(main_frame, text="抽奖显示")
        display_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))

        # 滚动显示标签
        self.display_label = tk.Label(
            display_frame,
            text="准备抽奖...",
            font=("Arial", 32, "bold"),
            fg="#FF5722",
            bg="#FFF9C4",
            relief=tk.RIDGE,
            padx=20,
            pady=20
        )
        self.display_label.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 结果显示区域
        result_frame = ttk.LabelFrame(main_frame, text="抽奖结果")
        result_frame.pack(fill=tk.BOTH, expand=True)

        # 创建结果表格
        columns = ("序号", "班级", "学号", "姓名")
        self.result_tree = ttk.Treeview(
            result_frame,
            columns=columns,
            show="headings",
            selectmode="extended"
        )

        # 设置列
        col_widths = [50, 200, 150, 150]
        for col, width in zip(columns, col_widths):
            self.result_tree.heading(col, text=col)
            self.result_tree.column(col, width=width, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.result_tree.yview)
        self.result_tree.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 状态栏
        self.status_var = tk.StringVar(value="就绪 | 共加载 0 名参与者")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def load_sample_data(self):
        # 创建一些示例数据
        sample_data = [
            {"班级": "计算机1班", "学号": "2023001", "姓名": "张三"},
            {"班级": "计算机1班", "学号": "2023002", "姓名": "李四"},
            {"班级": "计算机2班", "学号": "2023003", "姓名": "王五"},
            {"班级": "计算机2班", "学号": "2023004", "姓名": "赵六"},
            {"班级": "软件工程1班", "学号": "2023005", "姓名": "钱七"},
            {"班级": "软件工程1班", "学号": "2023006", "姓名": "孙八"},
            {"班级": "软件工程2班", "学号": "2023007", "姓名": "周九"},
            {"班级": "软件工程2班", "学号": "2023008", "姓名": "吴十"},
            {"班级": "人工智能1班", "学号": "2023009", "姓名": "郑十一"},
            {"班级": "人工智能1班", "学号": "2023010", "姓名": "王小明"},
        ]
        self.participants = sample_data
        self.status_var.set(f"已加载示例数据 | 共 {len(self.participants)} 名参与者")
        self.start_btn.config(state=tk.NORMAL)

    def import_excel(self):
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel文件", "*.xlsx *.xls"), ("所有文件", "*.*")]
        )

        if not file_path:
            return

        try:
            df = pd.read_excel(file_path)
            required_columns = ["班级", "学号", "姓名"]

            # 检查列名
            if not all(col in df.columns for col in required_columns):
                messagebox.showerror("错误", f"Excel文件必须包含以下列: {', '.join(required_columns)}")
                return

            # 转换为字典列表
            self.participants = df[required_columns].to_dict('records')
            self.winners = []  # 重置中奖者
            self.result_tree.delete(*self.result_tree.get_children())  # 清空结果列表

            self.status_var.set(f"成功导入数据 | 共 {len(self.participants)} 名参与者")
            self.start_btn.config(state=tk.NORMAL)
            self.display_label.config(text="数据导入成功！点击开始抽奖")

        except Exception as e:
            messagebox.showerror("错误", f"导入Excel文件时出错:\n{str(e)}")

    def start_lottery(self):
        if not self.participants:
            messagebox.showwarning("警告", "没有可用的参与者，请先导入数据！")
            return

        # 检查剩余人数
        remaining = len(self.participants) - len(self.winners)
        draw_count = self.draw_count.get()

        if draw_count > remaining:
            messagebox.showwarning("警告", f"剩余人数不足！\n剩余人数: {remaining}, 要求抽取: {draw_count}")
            return

        # 禁用按钮
        self.start_btn.config(state=tk.DISABLED)
        self.import_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.NORMAL)
        self.count_spin.config(state=tk.DISABLED)

        # 设置滚动状态
        self.is_rolling = True
        self.roll_speed = self.min_speed

        # 创建显示列表（随机顺序）
        self.display_list = random.sample(self.participants, len(self.participants))
        self.current_display_index = 0

        # 启动滚动线程
        threading.Thread(target=self.roll_display, daemon=True).start()

    def roll_display(self):
        while self.is_rolling:
            # 获取当前显示的人员
            person = self.display_list[self.current_display_index]
            info = f"{person['班级']} | {person['学号']} | {person['姓名']}"

            # 更新显示
            self.display_label.config(text=info)

            # 移动到下一个
            self.current_display_index = (self.current_display_index + 1) % len(self.display_list)

            # 逐渐加快速度
            if self.roll_speed > self.max_speed:
                self.roll_speed -= 1

            # 延迟
            time.sleep(self.roll_speed / 1000)

    def stop_lottery(self):
        if not self.is_rolling:
            return

        # 停止滚动
        self.is_rolling = False

        # 随机选择中奖者（不重复）
        draw_count = self.draw_count.get()
        candidates = [p for p in self.participants if p not in self.winners]
        new_winners = random.sample(candidates, draw_count)
        self.winners.extend(new_winners)

        # 显示中奖者
        if new_winners:
            winner_text = "\n\n".join([f"{w['班级']} | {w['学号']} | {w['姓名']}" for w in new_winners])
            self.display_label.config(text=f"中奖者：\n\n{winner_text}")

            # 添加到结果列表
            for i, winner in enumerate(new_winners, start=len(self.winners) - len(new_winners) + 1):
                self.result_tree.insert("", tk.END, values=(
                    i,
                    winner['班级'],
                    winner['学号'],
                    winner['姓名']
                ))

        # 更新状态
        remaining = len(self.participants) - len(self.winners)
        self.status_var.set(f"抽奖完成 | 共抽取 {len(self.winners)} 人 | 剩余 {remaining} 人")

        # 启用按钮
        self.start_btn.config(state=tk.NORMAL if remaining > 0 else tk.DISABLED)
        self.import_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.count_spin.config(state=tk.NORMAL)

    def reset_lottery(self):
        self.winners = []
        self.result_tree.delete(*self.result_tree.get_children())
        self.display_label.config(text="抽奖已重置！")

        remaining = len(self.participants)
        self.status_var.set(f"抽奖已重置 | 共 {remaining} 名参与者")
        self.start_btn.config(state=tk.NORMAL if remaining > 0 else tk.DISABLED)


def main():
    root = tk.Tk()
    app = LotteryApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()